<?php


namespace App\Http\Controllers\Api;


use App\Exceptions\ServiceException;
use App\Http\Constants\CommonExceptionConstants;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\DictationInputDTO;
use App\Util\ResultsVo;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Storage;
use OSS\OssClient;

class UploadController extends Controller
{
    private $ossClient;

    public function upload(Request $request) {

        $time = Carbon::now()->getTimestamp();

        $name = $request->get('name');

        $file = 'photo';

        if ($name){
            $file = $name;
        }

        $path = $request->file($file)->store(
            date('Y', $time).'-'.date('m', $time), 'uploads'
        );

        $data['url'] = config('app.url').'/uploads/'.$path;

        return response()->json(new ResultsVo(['data'=>$data,'message'=>Lang::get("response.success")]));
    }

    /**
     * 使用数组为参数上传文件（可一次上传多张）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadArray(Request $request){
        $time = Carbon::now()->getTimestamp();

        $file = $request->file('photo');

        $data = [];

        foreach ($file as $key=>$val){
            $path = $val->store(date('Y', $time).'-'.date('m', $time), 'uploads');
            $data[$key] = config('app.url').'/uploads/'.$path;
        }

        return response()->json(new ResultsVo(['data'=>$data,'message'=>Lang::get("response.success")]));
    }

    /**
     * 富文本编辑器使用的图片上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadArticle(Request $request){

        $time = Carbon::now()->getTimestamp();

        $path = $request->file('imgFile')->store(
            date('Y', $time).'-'.date('m', $time), 'uploads'
        );
        $data['error'] = 0;
        $data['url'] = config('app.url').'/uploads/'.$path;

        return response()->json($data);
    }

    /**
     * 图片上传保存到阿里云oss中
     * @param $ossKey
     * @param $pathFile
     * @throws \OSS\Core\OssException
     */
    public function ossUpload($ossKey, $pathFile) {
        if (getenv('APP_ENV') == 'production'  ) {
            $server = Config::get('oss.ossServerInternal');
        } else {
            $server = Config::get('oss.ossServer');
        }
        $this->ossClient = new OssClient(Config::get('oss.AccessKeyId'), Config::get('oss.AccessKeySecret'), $server, false);
        $this->ossClient->uploadFile(Config::get('oss.ossBucket'),$ossKey, $pathFile);
    }

    /**
     * 图片上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \OSS\Core\OssException
     */
    public function picture(Request $request) {
        $type = $request->get('type', 'dev');
        if ($request->hasFile('photo')) {
            if ($request->file('photo')->isValid()) {
                $pathDir = 'uploads/'.$type.'/'.date('Y', Carbon::now()->getTimestamp()).'/'.date('m', Carbon::now()->getTimestamp()).'/'.date('d', Carbon::now()->getTimestamp());
                $ext = $request->file('photo')->getClientOriginalExtension();
                if (empty($ext)) {
                    $ext = substr($_FILES['photo']['name'], strrpos($_FILES['photo']['name'], '.')+1);
                }
                $ossKey = $pathDir.'/'.$request->file('photo')->getFilename().'.'.$ext;
                $pathFile = $request->file('photo')->getRealPath();
                $data = [];
                if (1) {
                    $this->ossUpload($ossKey, $pathFile);
                    $data['url'] = Config::get('oss.ossHost').'/'.$ossKey;
                } else {
                    $bool = Storage::disk('public')->put($ossKey, file_get_contents($pathFile));
                    if ($bool) {
                        $data['url'] = getenv('APP_URL').'/'.$ossKey;
                    } else {
                        throw new ServiceException(CommonExceptionConstants::getKey('save_file_fail'));
                    }
                }
                return response()->json(new ResultsVo(['data'=>$data,'message'=>Lang::get('response.upload_success')]));
            } else {
                throw new ServiceException(CommonExceptionConstants::getKey('upload_file_invalid'));
            }
        } else {
            throw new ServiceException(CommonExceptionConstants::getKey('please_choose_file'));
        }
    }

    public function audio(Request $request){
        $type = $request->get('type', 'audio');
        if ($request->hasFile('audio')) {
            if ($request->file('audio')->isValid()) {
                $pathDir = 'uploads/'.$type.'/'.date('Y', Carbon::now()->getTimestamp()).'/'.date('m', Carbon::now()->getTimestamp()).'/'.date('d', Carbon::now()->getTimestamp());
                $ext = $request->file('audio')->getClientOriginalExtension();
                if (empty($ext)) {
                    $ext = substr($_FILES['audio']['name'], strrpos($_FILES['audio']['name'], '.')+1);
                }
                $ossKey = $pathDir.'/'.$request->file('audio')->getFilename().'.'.$ext;
                $pathFile = $request->file('audio')->getRealPath();
                $data = [];
                if (1) {
                    $this->ossUpload($ossKey, $pathFile);
                    $data['url'] = Config::get('oss.ossHost').'/'.$ossKey;
                } else {
                    $bool = Storage::disk('public')->put($ossKey, file_get_contents($pathFile));
                    if ($bool) {
                        $data['url'] = getenv('APP_URL').'/'.$ossKey;
                    } else {
                        throw new ServiceException(CommonExceptionConstants::getKey('save_file_fail'));
                    }
                }
                return response()->json(new ResultsVo(['data'=>$data,'message'=>Lang::get('response.upload_success')]));
            } else {
                throw new ServiceException(CommonExceptionConstants::getKey('upload_file_invalid'));
            }
        } else {
            throw new ServiceException(CommonExceptionConstants::getKey('please_choose_file'));
        }
    }

    public function video(Request $request){
        $type = $request->get('type', 'video');
        if ($request->hasFile('video')) {
            if ($request->file('video')->isValid()) {
                $pathDir = 'uploads/'.$type.'/'.date('Y', Carbon::now()->getTimestamp()).'/'.date('m', Carbon::now()->getTimestamp()).'/'.date('d', Carbon::now()->getTimestamp());
                $ext = $request->file('video')->getClientOriginalExtension();
                if (empty($ext)) {
                    $ext = substr($_FILES['video']['name'], strrpos($_FILES['video']['name'], '.')+1);
                }
                $ossKey = $pathDir.'/'.$request->file('video')->getFilename().'.'.$ext;
                $pathFile = $request->file('video')->getRealPath();
                $data = [];
                if (1) {
                    $this->ossUpload($ossKey, $pathFile);
                    $data['url'] = Config::get('oss.ossHost').'/'.$ossKey;
                } else {
                    $bool = Storage::disk('public')->put($ossKey, file_get_contents($pathFile));
                    if ($bool) {
                        $data['url'] = getenv('APP_URL').'/'.$ossKey;
                    } else {
                        throw new ServiceException(CommonExceptionConstants::getKey('save_file_fail'));
                    }
                }
                return response()->json(new ResultsVo(['data'=>$data,'message'=>Lang::get('response.upload_success')]));
            } else {
                throw new ServiceException(CommonExceptionConstants::getKey('upload_file_invalid'));
            }
        } else {
            throw new ServiceException(CommonExceptionConstants::getKey('please_choose_file'));
        }
    }

    /**
     * 语音转文字
     * @param DictationInputDTO $inputDTO
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function dictation(DictationInputDTO $inputDTO){
        #处理音频文件
        $filePath = $inputDTO->file('audio')->getRealPath();
        $fp = fopen($filePath, "rb");
        $audioContent = fread($fp,filesize($filePath));
        $audioBase64 = base64_encode($audioContent);

        $param= array(
            "aue"=>"raw",
            "engine_type"=>"sms16k",
        );
        $param = base64_encode(json_encode($param));
        $time = time();
        $appId = getenv('X-AppId');
        $appKey = getenv('X-AppKey');
        $checkSum = md5($appKey.$time.$param);
        $client = new Client(['base_uri' => 'https://api.xfyun.cn']);
        $response = $client->request('POST', '/v1/service/v1/iat', [
            'headers' => [
                'X-Appid' => $appId,
                'X-CurTime' => $time,
                'X-Param' => $param,
                'X-CheckSum' => $checkSum,
            ],
            'form_params' => [
                'audio' => $audioBase64,
            ]
        ]);

        $res = json_decode($response->getBody());

        $data = [];
        $data['data'] = $res->data;
        if ($res->code) {
            $message = $res->desc;
        }else{
            $message = Lang::get('response.success');
        }

        return response()->json(new ResultsVo(['data'=>$data,'code'=>$res->code,'message'=>$message]));
    }


}